const websocket = {
  state: {
    websocket: null, // WebSocket 对象
    isConnected: false, // 追踪连接状态
    wsUrl: "", // WebSocket URL
    gameResult: {}, // 游戏结果
  },

  mutations: {
    // 设置 WebSocket 对象
    setWebSocket(state, websocket) {
      state.websocket = websocket;
    },
    // 设置连接状态
    setConnectionStatus(state, status) {
      state.isConnected = status;
    },
    // 设置连接地址
    setWsUrl(state, url) {
      state.wsUrl = url;
    },
    // 设置游戏结果
    setGameResult(state, result) {
      state.gameResult = result;
    },
  },

  getters: {
    // 获取 WebSocket 对象
    getWebSocket(state) {
      return state.websocket;
    },
    // 获取连接状态
    getConnectionStatus(state) {
      return state.isConnected;
    },
    // 获取连接地址
    getWsUrl(state) {
      return state.wsUrl;
    },
    // 获取游戏结果
    getGameResult(state) {
      return state.gameResult;
    },
  },

  actions: {
    // 初始化 WebSocket 连接并设置监听事件
    initWebSocket({ state, commit, dispatch }) {
      // 防止重复连接
      if (state.isConnected) {
        return;
      }
      console.log("WebSocket 连接中...",state.isConnected);
      const Url = localStorage.getItem("wsUrl");
      const username = localStorage.getItem("username");
      const websocketUrl = Url + username;
      commit("setWsUrl", websocketUrl);

      const websocket = new WebSocket(state.wsUrl);
      commit("setWebSocket", websocket);

      websocket.onopen = () => {
        console.log("WebSocket 连接打开事件", state.wsUrl);
        commit("setConnectionStatus", true); // 设置连接状态为已连接
      };

      websocket.onmessage = (message) => {
        const data = JSON.parse(message.data);
        if (!data.body) {
          return;
        }
        if (typeof data.body === "string") {
          try {
            const body = JSON.parse(data.body);
            console.log("body:", body);
            if (body.status === "finish") {
              commit("setGameResult", body);
            }
          } catch (error) {
            console.log("body:", data.body);
            console.log("error:", error);
          }
        }
      };

      websocket.onclose = (e) => {
        console.log(e.code, e.reason, e.wasClean);
        console.log(state.wsUrl, "WebSocket 连接关闭");
        commit("setConnectionStatus", false); // 设置连接状态为断开
        commit("setWebSocket", null); // 清空 WebSocket 对象
        // 尝试重新连接
        setTimeout(() => {
          dispatch("initWebSocket");
        }, 5000); // 5秒后重新连接
      };

      websocket.onerror = (error) => {
        console.log(state.wsUrl, "WebSocket 发生错误", error);
        websocket.close(); // 关闭连接并触发 onclose 事件
      };
    },
  },
};

export default websocket;
